/**
 * 
 */
package org.dragonfire.irc.messages;

/**
 * @author Darth Android
 * @date Oct 27, 2007
 */
public class Message {

	public static Message parseMessage(String msg) {
		if (msg == null || msg.length() == 0)
			throw new NullPointerException("Input string may not be null");
		String prefix = "", command = "";
		if (msg.charAt(0) == ':') {
			int end = msg.indexOf(' ');
			if (end < 0)
				throw new MessageFormatException("No command following prefix.");
			prefix = msg.substring(1, end);
			msg = msg.substring(end);
		}
		{
			int end = msg.indexOf(' ');
			if (end < 0)
				end = msg.length();
			command = msg.substring(0, end);
		}
		String[] params;
		{
			int colon = msg.indexOf(':');
			String post = null;
			if (colon > -1) {
				post = msg.substring(colon + 1, msg.length());
				msg = msg.substring(0, colon);
			}
			String[] tmpParam = msg.split("\\s+");
			params = new String[tmpParam.length + (post == null ? 0 : 1)];
			System.arraycopy(tmpParam, 0, params, 0, tmpParam.length);
			if (post != null)
				params[tmpParam.length] = post;

		}
		if (command.length() == 0)
			throw new MessageFormatException("No command in message");
		command = command.intern();
		return new Message(prefix, command, params);
	}

	private String prefix, command;
	private String[] params;

	/**
	 * @return the prefix
	 */
	public String getPrefix() {
		return prefix;
	}

	/**
	 * @param prefix
	 * @param command
	 * @param params
	 */
	public Message(String prefix, String command, String... params) {
		super();
		this.prefix = prefix;
		this.command = command;
		this.params = params;
	}

	public Message(String prefix, int command, String... params) {
		this(prefix, command + "", params);
	}

	public Message(Message clone) {
		this(clone.getPrefix(), clone.getCommand(), clone.getParams());
	}

	/**
	 * @return the command
	 */
	public String getCommand() {
		return command;
	}

	/**
	 * @return the params
	 */
	public String[] getParams() {
		return params;
	}

	/**
	 * @param prefix
	 *            the prefix to set
	 */
	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	/**
	 * @param command
	 *            the command to set
	 */
	public void setCommand(String command) {
		this.command = command;
	}

	/**
	 * @param params
	 *            the params to set
	 */
	public void setParams(String[] params) {
		this.params = params;
	}

}
